package com.shen.accountbook.module.home.booknote;

import android.content.Context;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.shen.accountbook.R;
import com.shen.accountbook.bean.temp.NoteBeanTemp;
import com.shen.accountbook.bean.temp.SecondSortBean;
import com.shen.accountbook.bean.temp.ThirdSortBean;
import com.shen.accountbook.greendao.DaoSession;
import com.shen.accountbook.greendao.manager.DaoManager;
import com.shen.accountbook.module.base.MVPActivity;
import com.shen.accountbook.utils.DateUtils;
import com.shen.accountbook.utils.FormatUtils;
import com.shen.accountbook.utils.StringUtils;
import com.shen.accountbook.utils.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;

import static com.shen.accountbook.config.Constant.INTENT_BEAN;
import static com.shen.accountbook.config.Constant.TYPE_ADD;
import static com.shen.accountbook.config.Constant.TYPE_CHANGE;
import static com.shen.accountbook.config.Constant.TYPE_OUTPUT;
import static com.shen.accountbook.config.Constant.TYPE_INPUT;
import static com.shen.accountbook.utils.DateUtils.FORMAT2;

/**
 * author:  initPhotoPicker
 * date:    2018/8/28
 */
public class BookNoteActivity extends MVPActivity<BookNotePresenterImpl> implements BookNoteView {


    /** 标题上的"收入" */
    @BindView(R.id.tv_note_income_booknote)
    TextView mTvIncome;
    /** 标题上的"支出" */
    @BindView(R.id.tv_note_outcome_booknote)
    TextView mTvOutcome;

    /** 备注 */
    @BindView(R.id.et_note_remark_booknote)
    EditText mEtNoteRemark;
    /** 金额 */
    @BindView(R.id.tv_note_money_booknote)
    TextView mTvMoney;

    /** 时间 */
    @BindView(R.id.tv_note_date_booknote)
    TextView mTvDate;

    /** "收入/支出"的类型列表 */
    @BindView(R.id.vp_item_booknote)
    ViewPager mViewPager;
    /** viewpage 的 指示器 */
    @BindView(R.id.layout_icon)
    LinearLayout mLayoutIndicator;
    /** 放图片的列表 */
    @BindView(R.id.rv_photo)
    RecyclerView mRvPhoto;

    LayoutInflater mLayoutInflater;

    long mSelectThirdId = -1;
    ThirdSortBean mThirdSortBean = null;
    /* 类型 */
    private List<View> mViewList;
    private List<ThirdSortBean> mThirdSortBeanListTop;
    private List<List<ThirdSortBean>> mThirdSortBeanListList;
    private List<BookNoteAdapter> mAdapterList;
    private ImageView[] mIndicators;

    /* 计算器 */
    /** 输入了几个字符(是点击输入的，不是显示的字符，点击删除是会 -1) */
    private int mNumCount = 0;
    private boolean isDot;
    private String mNum = "0";
    private String mDotNum = ".00";
    private final int MAX_NUM = 9999999;
    private final int DOT_NUM = 2;

    private NoteBeanTemp mNoteBeanTemp;

    /* 图片选择器 */
    private PhotoAdapter mPhotoAdapter;
    private ArrayList<String> mSelectedPhotos = new ArrayList<>();

    Date mDate = new Date();
    Calendar mCalendar;


    int mType = TYPE_ADD;

    @Override
    protected BookNotePresenterImpl createPresenter(Context context) {
        return new BookNotePresenterImpl(context, this);
    }

    @Override
    protected int getResId() {
        return R.layout.activity_book_note;
    }

    @Override
    protected void initData() {
        getIntentData();
    }


    @Override
    protected void initEvent() {
        if(mNoteBeanTemp != null){
            mType = TYPE_CHANGE;
            mSelectThirdId = mNoteBeanTemp.getThird_sort_id();

            DaoSession daoSession = DaoManager.getInstance().getSession();
            mNoteBeanTemp.__setDaoSession(daoSession);
            mThirdSortBean = mNoteBeanTemp.getThirdSortBean();

            initType(TYPE_OUTPUT);
            setTime(DateUtils.parse(mNoteBeanTemp.getCreateDate(), FORMAT2));
            mEtNoteRemark.setText(mNoteBeanTemp.getRemarks());
            mTvMoney.setText(FormatUtils.float2DecimalFormat(mNoteBeanTemp.getMoney(), 2));
        }else {
            initType(TYPE_OUTPUT);
            setTime(new Date());
        }
    }


    private void getIntentData(){
        Intent intent = getIntent();
        mNoteBeanTemp = intent.getParcelableExtra(INTENT_BEAN);
    }


    private void initType(int type){
        initViewList(type);
        initViewPager();
        initPhotoPicker();

//        /** 备注 */
//        @BindView(R.id.et_note_remark_booknote)
//        EditText mEtNoteRemark;
//        /** 金额 */
//        @BindView(R.id.tv_note_money_booknote)
//        TextView mTvMoney;
    }

    private void initViewList(int type){
        mLayoutInflater = getLayoutInflater();     // 获得一个视图管理器LayoutInflater
        mViewList = new ArrayList<>();
        mAdapterList = new ArrayList<>();

        mThirdSortBeanListTop = mPresenter.getThirdSortBeanByFirstIdFrequency(type);
        mThirdSortBeanListList = mPresenter.getThirdSortBeanByFirstIdSecondIdList(type);

        if(mThirdSortBeanListTop != null){
            setViewList(mThirdSortBeanListTop, "常用");
        }

        // 三级分类放到二级分类界面中
        for(List<ThirdSortBean> list : mThirdSortBeanListList){
            if(list != null && list.size() > 0){
                setViewList(list, list.get(0).getThird_sort_name());
            }
        }
    }


    /**
     * 每一个二级分类界面
     * @param beanList
     * @param title
     */
    private void setViewList(List<ThirdSortBean> beanList, String title){
        View view = mLayoutInflater.inflate(R.layout.pager_item_type, null);
        TextView textView = view.findViewById(R.id.tv_title_pageritemtype);
        textView.setText(title);
        RecyclerView recycle = view.findViewById(R.id.rv_pager_type_pageritemtype);
        BookNoteAdapter adapter = new BookNoteAdapter(this, beanList,
                new BookNoteAdapter.ItemClickListener() {
                    @Override
                    public void itemClick(BookNoteAdapter adapter, ThirdSortBean bean) {
                        mSelectThirdId = bean.getThird_sort_id();
                        mThirdSortBean = bean;
                        setAdapterList();
                    }
                });
        GridLayoutManager layoutManager = new GridLayoutManager(this, 5);
        recycle.setLayoutManager(layoutManager);
        recycle.setAdapter(adapter);
        mAdapterList.add(adapter);
        mViewList.add(view);
    }

    /**
     * 刷新所有的页中的列表，因为某一个列表的项被选中，所以其他的都要清空
     */
    private void setAdapterList(){
        if(mAdapterList != null){
            for(BookNoteAdapter adapter : mAdapterList){
                if(adapter != null){
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }

    private void initViewPager(){
        mViewPager.setAdapter(new SortPagerAdapter(mViewList));
        mViewPager.setOverScrollMode(View.OVER_SCROLL_NEVER);
        mViewPager.setOffscreenPageLimit(1);//预加载数据页
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                try {

                    if(mIndicators != null && mIndicators.length > position){
                        for(int i = 0; i < mIndicators.length; i++){
                            if(i == 0){
                                mIndicators[i].setImageResource(R.drawable.icon_banner_heart2);
                            }else {
                                mIndicators[i].setImageResource(R.drawable.icon_banner_point2);
                            }
                        }

                        if(position == 0){
                            mIndicators[position].setImageResource(R.drawable.icon_banner_heart1);
                        }else {
                            mIndicators[position].setImageResource(R.drawable.icon_banner_point1);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        initIndicator();
    }

    private void initIndicator() {
        mIndicators = new ImageView[mViewList.size()];
        mLayoutIndicator.removeAllViews();
        for (int i = 0; i < mIndicators.length; i++) {
            mIndicators[i] = new ImageView(this);
            mIndicators[i].setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

            if(i == 0){
                mIndicators[i].setImageResource(R.drawable.icon_banner_heart2);
                if(mViewPager.getCurrentItem() == i){
                    mIndicators[i].setImageResource(R.drawable.icon_banner_heart1);
                }
            }else {
                mIndicators[i].setImageResource(R.drawable.icon_banner_point2);
                if (mViewPager.getCurrentItem() == i) {
                    mIndicators[i].setImageResource(R.drawable.icon_banner_point1);
                }
            }
            mIndicators[i].setPadding(5, 0, 5, 0);
            mIndicators[i].setAdjustViewBounds(true);
            mLayoutIndicator.addView(mIndicators[i]);
            setIndicatorListen(mIndicators[i], i);
        }
    }

    private void setIndicatorListen(ImageView view, final int position){
        if(view != null){
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mViewPager != null && mViewPager.getChildCount() > position){
                        mViewPager.setCurrentItem(position);
                    }
                }
            });
        }
    }


    @OnClick({
            R.id.tv_note_income_booknote, R.id.tv_note_outcome_booknote,
            R.id.tv_note_date_booknote, R.id.tv_done_keyboardnumber,
            R.id.rlayout_del_keyboardnumber, R.id.tv_num_1_keyboardnumber,
            R.id.tv_num_2_keyboardnumber, R.id.tv_num_3_keyboardnumber,
            R.id.tv_num_4_keyboardnumber, R.id.tv_num_5_keyboardnumber,
            R.id.tv_num_6_keyboardnumber, R.id.tv_num_7_keyboardnumber,
            R.id.tv_num_8_keyboardnumber, R.id.tv_num_9_keyboardnumber,
            R.id.tv_num_0_keyboardnumber, R.id.tv_num_dot_keyboardnumber,
            R.id.iv_note_clear_booknote, R.id.iv_back_booknote})
    protected void onClick(View view){
        switch (view.getId()){
            case R.id.iv_back_booknote:
                finish();
                break;

            case R.id.tv_note_income_booknote:              /* 收入 */
                initType(TYPE_INPUT);
                break;

            case R.id.tv_note_outcome_booknote:             /* 支出 */
                initType(TYPE_OUTPUT);
                break;

            case R.id.tv_note_date_booknote:                /* 日期 */
                selectTime();
                break;

            case R.id.tv_done_keyboardnumber:               /* 确定 */
                clickKeyBoardDone();
                break;

            case R.id.tv_num_1_keyboardnumber:
                calcMoney(1);
                break;
            case R.id.tv_num_2_keyboardnumber:
                calcMoney(2);
                break;
            case R.id.tv_num_3_keyboardnumber:
                calcMoney(3);
                break;
            case R.id.tv_num_4_keyboardnumber:
                calcMoney(4);
                break;
            case R.id.tv_num_5_keyboardnumber:
                calcMoney(5);
                break;
            case R.id.tv_num_6_keyboardnumber:
                calcMoney(6);
                break;
            case R.id.tv_num_7_keyboardnumber:
                calcMoney(7);
                break;
            case R.id.tv_num_8_keyboardnumber:
                calcMoney(8);
                break;
            case R.id.tv_num_9_keyboardnumber:
                calcMoney(9);
                break;
            case R.id.tv_num_0_keyboardnumber:
                calcMoney(0);
                break;

            case R.id.tv_num_dot_keyboardnumber:                /* 点击"." */
                clickKeyBoardDot();
                break;

            case R.id.iv_note_clear_booknote:                   /* 清空 */
                clearKeyboard();
                break;

            case R.id.rlayout_del_keyboardnumber:               /* 删除 */
                delKeyboard();
                break;
        }
    }

    /**
     * 删除
     */
    private void delKeyboard() {
        if (isDot){
            if (mNumCount > 0){
                mDotNum = mDotNum.substring(0, mDotNum.length() - 1);
                mNumCount--;
            }
            if (mNumCount == 0){
                isDot = false;
                mDotNum = ".00";
            }
            mTvMoney.setText(mNum + mDotNum);
        }else {
            if (mNum.length() > 0)
                mNum = mNum.substring(0, mNum.length() - 1);
            if (mNum.length() == 0)
                mNum = "0";
            mTvMoney.setText(mNum + mDotNum);
        }
    }

    /**
     * 清空
     */
    private void clearKeyboard() {
        mNum = "0";
        mNumCount = 0;
        mDotNum = ".00";
        isDot = false;
        mTvMoney.setText("0.00");
    }

    /**
     *  点击"."
     */
    private void clickKeyBoardDot() {
        if (mDotNum.equals(".00")){
            isDot = true;
            mDotNum = ".";
        }
        mTvMoney.setText(mNum + mDotNum);
    }

    /**
     *  点击"确定"后，如果是"."要改为".00"
     */
    private void clickKeyBoardDone() {
        if (mDotNum.equals(".")){
            isDot = false;
            mDotNum = ".00";
            mTvMoney.setText(mNum + mDotNum);
        }


        String money = mTvMoney.getText().toString().trim();
        String remarks = mEtNoteRemark.getText().toString().trim();
        String date = mTvDate.getText().toString().trim();

        if(mSelectThirdId == -1 || mThirdSortBean == null){
            ToastUtils.showToast("请选择类型");
            return;
        }
        if(StringUtils.isEmpty(money) || money.equals("0.00")){
            ToastUtils.showToast("输入金额");
            return;
        }


        if(mType == TYPE_ADD) {
            NoteBeanTemp bean = new NoteBeanTemp();

            DaoSession daoSession = DaoManager.getInstance().getSession();
            mThirdSortBean.__setDaoSession(daoSession);
            SecondSortBean secondSortBean = mThirdSortBean.getSecondSortBean();
            if (secondSortBean == null) {
                ToastUtils.showToast("记账失败");
                return;
            }
            bean.setFirst_sort_id(secondSortBean.getFirst_sort_id());
            bean.setSecond_sort_id(mThirdSortBean.getSecond_sort_id());
            bean.setThird_sort_id(mThirdSortBean.getThird_sort_id());
            bean.setMoney(FormatUtils.str2Float(money));
            bean.setRemarks(remarks);
            bean.setCreateDate(date);
            bean.setImg(StringUtils.listToString(mSelectedPhotos));

            if (mPresenter.insertNoteBean(bean)) {
                ToastUtils.showToast("记账成功");
                mPresenter.updateFrequency(mThirdSortBean.getThird_sort_id());
            } else {
                ToastUtils.showToast("记账失败");
            }
        }else {
            DaoSession daoSession = DaoManager.getInstance().getSession();
            mThirdSortBean.__setDaoSession(daoSession);
            SecondSortBean secondSortBean = mThirdSortBean.getSecondSortBean();
            if (secondSortBean == null) {
                ToastUtils.showToast("更新失败");
                return;
            }
            mNoteBeanTemp.setFirst_sort_id(secondSortBean.getFirst_sort_id());
            mNoteBeanTemp.setSecond_sort_id(mThirdSortBean.getSecond_sort_id());
            mNoteBeanTemp.setThird_sort_id(mThirdSortBean.getThird_sort_id());
            mNoteBeanTemp.setMoney(FormatUtils.str2Float(money));
            mNoteBeanTemp.setRemarks(remarks);
            mNoteBeanTemp.setCreateDate(date);
            mNoteBeanTemp.setImg(StringUtils.listToString(mSelectedPhotos));

            try {
                mPresenter.update(mNoteBeanTemp);
                ToastUtils.showToast("更新成功");
            }catch (Exception e){
                ToastUtils.showToast("更新失败");
            }
        }
    }


    private void calcMoney(int money) {
        if (mNum.equals("0") && money == 0)              // 一开始的时候点击"0" 不处理
            return;

        if (isDot) {                                    /* 点击了"." -- 输入的数组都是小数了 */
            if (mNumCount < DOT_NUM) {                      // 如果是小于两位小数，就处理，大于或等于就不处理
                mNumCount++;
                mDotNum += money;
                mTvMoney.setText(mNum + mDotNum);
            }

        }else if (Integer.parseInt(mNum) < MAX_NUM) {    /* 非点击了"." */
            if (mNum.equals("0"))
                mNum = "";
            mNum += money;
            mTvMoney.setText(mNum + mDotNum);
        }
    }


    /**
     * 选择日期
     */
    private void selectTime() {
        TimePickerView startTimePicker = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                setTime(date);
            }
        }).setRange(2018,2050)
                .setType(new boolean[]{true,true,true,false,false,false})
                .build();

        startTimePicker.setDate(mCalendar);
        startTimePicker.show();
    }

    private void setTime(Date date){
        mDate = date;
        mCalendar = Calendar.getInstance();
        mCalendar.setTime(date);
        String weekStr = DateUtils.getWeekStr(mCalendar);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        mTvDate.setText(sdf.format(date));
    }

    private void initPhotoPicker() {
//        if(mPhotoAdapter != null && mSelectedPhotos != null){
//            mSelectedPhotos.clear();
//            mPhotoAdapter.notifyDataSetChanged();
//            return;
//        }
        if(mNoteBeanTemp != null){
            String image = mNoteBeanTemp.getImg();
            if(StringUtils.isNotEmpty(image)){
                mSelectedPhotos = StringUtils.stringToList(image.split(","));
            }
        }

        mPhotoAdapter = new PhotoAdapter(this, mSelectedPhotos, PhotoAdapter.TYPE_IMPORT);

        mRvPhoto.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));
        mRvPhoto.setAdapter(mPhotoAdapter);

        mRvPhoto.addOnItemTouchListener(new RecyclerItemClickListener(this,
                new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        if (mPhotoAdapter.getItemViewType(position) == PhotoAdapter.ITEM_ADD) {
                            PhotoPicker.builder()
                                    .setPhotoCount(PhotoAdapter.MAX)
                                    .setShowCamera(true)
                                    .setPreviewEnabled(false)
                                    .setSelected(mSelectedPhotos)
                                    .start(mActivity);
                        } else {
                            PhotoPreview.builder()
                                    .setPhotos(mSelectedPhotos)
                                    .setCurrentItem(position)
                                    .start(mActivity);
                        }
                    }
                }));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK &&
                (requestCode == PhotoPicker.REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {

            List<String> photos = null;
            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            }
            mSelectedPhotos.clear();

            if (photos != null) {
                mSelectedPhotos.addAll(photos);
            }
            mPhotoAdapter.notifyDataSetChanged();
        }
    }
}
